<?php

class Mithos_Guild {
    private $_id;
    private $_name;
    private $_score;
    private $_master;
    private $_notice;
    private $_mark;
    private $_members = array();
    private $_data = array();

    public function __construct($name = null) {
        if ($name !== null) {
            $this->read($name);
        }
    }

    public function id($id = null) {
        if ($id === null) {
            return $this->_id;
        }
        $this->_id = $id;
        return $this;
    }

    public function name($name = null) {
        if ($name === null) {
            return $this->_name;
        }
        $this->_name = $name;
        return $this;
    }

    public function score($score = null) {
        if ($score === null) {
            return $this->_score;
        }
        $this->_score = $score;
        return $this;
    }

    public function master($master = null) {
        if ($master === null) {
            if (!$this->_master instanceof Mithos_Character) {
                return new Mithos_Character($this->_master);
            }
            return $this->_master;
        }
        $this->_master = $master;
        return $this;
    }

    public function notice($notice = null) {
        if ($notice === null) {
            return $this->_notice;
        }
        $this->_notice = $notice;
        return $this;
    }

    public function mark($mark = null) {
        if ($mark === null) {
            return $this->_mark;
        }
        $this->_mark = $mark;
        return $this;
    }

    public function members() {
        $results = Mithos_Mssql::getInstance()->fetchAll('SELECT Name as name 
            FROM GuildMember
            WHERE G_Name = :name[string]
        ', array('name' => $this->name()));
        if (!empty($results)) {
            foreach ($results as $result) {
                $this->_members[] = new Mithos_Character($result['name']);
            }
        }
        return $this->_members;
    }

    public function count($where = null) {
        $where = $where !== null ? ' WHERE ' . $where : '';
        $result = Mithos_Mssql::getInstance()->fetch('SELECT 
            COUNT(1) AS total FROM Guild
        ' . $where);
        return $result['total'];
    }

    public function read($name) {
        $result = Mithos_Mssql::getInstance()->fetch('SELECT 
            g.Number AS id,
            g.G_Score AS score,
            g.G_Notice AS notice,
            g.G_Name AS name,
            g.G_Master AS master,
            g.G_Mark AS mark
            FROM Guild g
            WHERE g.G_Name = :name[string]
        ', array('name' => $name));
        if (!empty($result)) {
            $this->_data = $result;
            foreach ($result as $key => $value) {
                if (method_exists($this, $key)) {
                    $this->{$key}($value);
                }
            }
        }
    }
}

?>